package com.yuanchu.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.goods.dao.YoshopGoodsSkuDao;
import com.yuanchu.goods.dto.GoodsSkuDto;
import com.yuanchu.goods.entity.YoshopGoodsImageEntity;
import com.yuanchu.goods.entity.YoshopGoodsSkuEntity;
import com.yuanchu.goods.entity.YoshopUploadFileEntity;
import com.yuanchu.goods.service.YoshopGoodsImageService;
import com.yuanchu.goods.service.YoshopGoodsSkuService;
import com.yuanchu.goods.service.YoshopUploadFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yuanchu.common.utils.DateFormatUtils.formatDatetime;


@Service("yoshopGoodsSkuService")
public class YoshopGoodsSkuServiceImpl extends ServiceImpl<YoshopGoodsSkuDao, YoshopGoodsSkuEntity> implements YoshopGoodsSkuService {

    @Resource
    private YoshopUploadFileService yoshopUploadFileService;

    @Resource
    private YoshopGoodsImageService goodsImageService;
    @Resource
    private YoshopGoodsSkuDao goodsSkuDao;


    @Override
    public List<GoodsSkuDto> getSkuListById(Integer goodsId) {
        List<YoshopGoodsSkuEntity> skuEntities = this.list(new QueryWrapper<YoshopGoodsSkuEntity>().eq("goods_id", goodsId));
        if (CollectionUtils.isEmpty(skuEntities)){
            return Collections.emptyList();
        }
        return skuEntities.stream().map(sku -> {
            GoodsSkuDto goodsSkuDto = new GoodsSkuDto();
            BeanUtils.copyProperties(sku, goodsSkuDto);
            goodsSkuDto.setGoodsProps(this.getGoodsProps(sku.getGoodsProps()));
            goodsSkuDto.setSpecValueIds(this.getSpecValueIds(sku.getSpecValueIds()));
            goodsSkuDto.setCreateTime(formatDatetime(sku.getCreateTime()));
            goodsSkuDto.setUpdateTime(formatDatetime(sku.getUpdateTime()));
            Integer imageId = sku.getImageId();
            if (imageId == null || imageId == 0){
                // 默认商品图片
                List<YoshopGoodsImageEntity> imagelist = goodsImageService.list(new QueryWrapper<YoshopGoodsImageEntity>().eq("goods_id", goodsId));
                imageId = imagelist.get(0).getImageId();
            }
            YoshopUploadFileEntity file = yoshopUploadFileService.getUploadFileById(imageId);
            goodsSkuDto.setImage(file);
            goodsSkuDto.setGoodsImage(file.getPreviewUrl());
            goodsSkuDto.setImageUrl(file.getPreviewUrl());
            return goodsSkuDto;
        }).collect(Collectors.toList());
    }

    private List<Integer> getSpecValueIds(String specValueIdsStr) {
        if (StringUtils.isEmpty(specValueIdsStr)){
            return Collections.emptyList();
        }
        // 使用Fastjson的JSONArray.parseArray方法解析字符串
        JSONArray jsonArray = JSONArray.parseArray(specValueIdsStr);

        // 将JSONArray转换为Integer数组
        // Integer[] specValueIdsArray = jsonArray.toArray(new Integer[0]);

        // 或者将其转换为List<Integer>
        List<Integer> specValueIdsList = jsonArray.toJavaList(Integer.class);

        return specValueIdsList;
    }

    /**
     * 解析商品属性
     * @param props
     * @return
     */
    public List<Map<String, Object>> getGoodsProps(String props) {
        // 解析JSON数组到List<Map<String, Object>>
        JSONArray jsonArray = JSONArray.parseArray(props);
        if (StringUtils.isEmpty(props)){
            return Collections.emptyList();
        }
        List<Map<String, Object>> specItemsAsMaps = new ArrayList<>();

        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            Map<String, Object> itemMap = jsonObject.toJavaObject(Map.class);
            // 将嵌套的对象也转为Map
            Map<String, Object> groupMap = ((JSONObject) itemMap.get("group")).toJavaObject(Map.class);
            Map<String, Object> valueMap = ((JSONObject) itemMap.get("value")).toJavaObject(Map.class);

            // 将group和value替换为它们对应的Map对象
            itemMap.put("group", groupMap);
            itemMap.put("value", valueMap);

            specItemsAsMaps.add(itemMap);
        }

        // 现在specItemsAsMaps包含了从JSON字符串中解析出来的Map对象数组
        /*for (Map<String, Object> item : specItemsAsMaps) {
            Map<String, Object> group = (Map<String, Object>) item.get("group");
            Map<String, Object> value = (Map<String, Object>) item.get("value");

            System.out.println(group.get("name") + ": " + value.get("name"));
        }
        System.out.println(specItemsAsMaps.toString());*/
        // return specItemsAsMaps.toString();
        return specItemsAsMaps;
    }

    @Override
    public GoodsSkuDto queryGoodsSku(Integer skuId) {
        YoshopGoodsSkuEntity goodsSkuEntity = this.getById(skuId);
        GoodsSkuDto goodsSkuDto = new GoodsSkuDto();
        BeanUtils.copyProperties(goodsSkuEntity, goodsSkuDto);
        return goodsSkuDto;
    }

    @Override
    @Transactional
    public boolean decrStockNum(Integer goodsId, String goodsSkuId, Integer num) {
        Integer updated = goodsSkuDao.updateGoodsSkuStockNum(goodsId, goodsSkuId, num);
        return updated > 0;
    }

}